package com.houseman.workFlow.opening.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.houseman.workFlow.dto.WorkFlowInfo;
import com.houseman.workFlow.opening.WorkFlow;
import com.houseman.workFlow.utils.DBUtils;

public class WorkFlowImpl implements WorkFlow{

	/**
	 * 根据用户Id查询该用户可以发起的流程信息
	 * @param userId
	 * @return
	 */
	public List<WorkFlowInfo> queryStartByUserId(String userId) {
		List<WorkFlowInfo> mine = new ArrayList<WorkFlowInfo>();
		try {
			//获得连接
			Connection conn = DBUtils.geConnection();
			
			PreparedStatement ps = conn.prepareStatement("SELECT G.GRAPHID,G.NAME FROM WORKFLOWGRAPH G,USERROLE R WHERE G.APPROLE=R.ROLEID AND R.USERID=?");
			ps.setString(1, userId);
			
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				WorkFlowInfo info = new WorkFlowInfo();
				info.setGraphId(rs.getInt("GRAPHID"));
				info.setName(rs.getString("NAME"));
				
				mine.add(info);
			}
			
			//关闭连接
			DBUtils.close(conn, ps, rs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mine;
	}
	
	/**
	 * 根据用户Id查询等待该用户处理的流程
	 * @param userId
	 * @return
	 */
	public List<WorkFlowInfo> queryWaitingByUserId(String userId) {
		List<WorkFlowInfo> wait = new ArrayList<WorkFlowInfo>();
		try {
			//获得连接
			Connection conn = DBUtils.geConnection();
			
			PreparedStatement ps = conn.prepareStatement("SELECT W.WORKID,U.USERNAME,W.NAME FROM WORKFLOW W,USER U WHERE U.USERID=W.CREATER AND STATUS<>1 AND W.APPROVER=?");
			ps.setString(1, userId);
			
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				WorkFlowInfo info = new WorkFlowInfo();
				info.setWorkId(rs.getInt("WORKID"));
				info.setUserName(rs.getString("USERNAME"));
				info.setName(rs.getString("NAME"));
				
				wait.add(info);
			}
			
			//关闭连接
			DBUtils.close(conn, ps, rs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return wait;
	}
}
